package com.example.socketdemo;

import android.os.Handler;
import android.os.Message;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.Socket;

public class SendNumberThread extends Thread{

    Handler handler;
    private Socket socket = null;
    private String code;
    private byte[] data;
    public static byte[] receiveByte;
    public static byte[] receiveByteSM=new byte[0];

    public SendNumberThread(Socket s,Handler handler,byte[] data,String code){
        this.socket = s;
        this.handler = handler;
        this.code = code;
        this.data = data;
    }

    @Override
    public void run() {
        try{
            if (socket.isConnected()) {
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                out.write(data);
                out.flush();
                DataInputStream in = new DataInputStream(socket.getInputStream());
                byte[] bytes = new byte[64];
                in.read(bytes);
                this.receiveByteSM=bytes;
                if (bytes.length != 0 && bytes[0] == 6) {
                    Message msg = handler.obtainMessage();
                    msg.what = 6; //发送信息成功标志
                    msg.obj = code;
                    handler.sendMessage(msg);
                }else{
                    Message msg = handler.obtainMessage();
                    msg.what = 2; //发送信息失败标志
                    msg.obj = "发送数据失败";
                    handler.sendMessage(msg);
                }
            } else {
                Message msg = handler.obtainMessage();
                msg.what = 5; //发送消息断开标志
                msg.obj = "发送连接断开";
                handler.sendMessage(msg);
            }
        }catch (Exception e){
            Message msg = handler.obtainMessage();
            msg.what = 3; //发送消息断开标志
            msg.obj = "发送数据异常";
            handler.sendMessage(msg);
        }
    }
}
